package aws;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Dictionary {

    public static void main(String[] args) {
        String []array = new String[]{"DAMP", "LAMP","LIMP","LIME","LIKE","abcd","abc","ab"};
        String []sourceArray = new String[]{"DAMP","LIKE"};
//        new Dictionary().filter("LIKE", Arrays.asList(array)).stream().forEach(item->{
//            System.out.print(item + " ");
//        });
        new Dictionary().ff(Arrays.asList(sourceArray), Arrays.asList(array));
    }

    public void ff(List<String> source, List<String> dic) {
        for(int i=0; i<source.size(); i++) {
           List<String> result = filter(source.get(i), dic);
           result.stream().forEach(item->{
               System.out.print(item + " ");
           });
            System.out.println();
        }
    }

    /**
     * 输入四个字符，在字典中找到一样或者其中一个字符不一样的，
     * 并以找到的字符重复查找，并输出他们
     * @param
     * @param dic
     * @return
     */
    public List<String> filter(String str, List<String> dic) {

        //存放dic中已经match的字符串
        List<String> matched = new ArrayList<>();
        List<String> resultList = new ArrayList<>();
        for(int i =0; i<dic.size(); i++) {
            String test = dic.get(i);
            if(matched.contains(test)) {
                continue;
            }
            String result = find(str, test);
            if(!"".equals(result)) {
                //把找到的字符加到结果里
                resultList.add(result);
                //已经找过的，不能再找了
                matched.add(result);
                //重置条件，重新查找
                str = result;
                i = 0;
            }
        }
        return resultList;
    }

    /**
     * 两个字符是否匹配
     * @param str
     * @param test
     * @return
     */
    public String find(String str, String test) {
        if(str.equals(test)) {
            return test;
        }
        if(str.length() != test.length()) {
            return "";
        }

        //记录有几个单词不一样
        int times=0;
        for(int index=0; index<str.length(); index++) {
            if(times >=2) {
                return "";
            }
            Character sc = str.charAt(index);
            Character tc = test.charAt(index);
            if(sc == tc) {
                continue;
            } else {
                times = times + 1;
            }
        }
        if(times <=1) {
            return test;
        } else {
            return "";
        }
    }
}
